// pages/productDetail/productDetail.js
Page({
  data: {
    globalData: getApp().globalData,
    product: {},
    customerFlag: true,
    buyFlag: true,
    buy: true,
    count: 1
  },

  onLoad(options) {
    this.getProduct(options.id)
  },

  getProduct(id) {
    var that = this
    wx.request({
      url: that.data.globalData.server + '/product/' + id,
      method: 'GET',
      success(res) {
        that.setData({product: res.data.data,})
      }
    })
  },
  showCustomer() {
    this.setData({customerFlag: false})
  },
  hideCustomer() {
    this.setData({customerFlag: true})
  },
  showCar() {
    this.setData({buyFlag: false, buy: false})
  },
  showBuy() {
    this.setData({buyFlag: false, buy: true})
  },
  hideBuy() {
    this.setData({buyFlag: true})
  },
  minus() {
    if (this.data.count > 1)
      this.setData({count: this.data.count - 1})
  },
  plus() {
    this.setData({count: this.data.count + 1})
  },
  toShopcar() {
    wx.redirectTo({url: '/pages/shopcar/shopcar',})
  },
  submit() {
    if(wx.getStorageSync('user') == '') {
      wx.showModal({
        title: '提示',
        content: '请登录后购买',
        complete: (res) => {
          if (res.confirm) {
            wx.navigateTo({url: '/pages/login/login',})
          } else if (res.cancel) {
            return
          }
        }
      })
    } else {
      if(this.data.buy) {  //购买
        this.data.product.count = this.data.count
        // let list = [this.data.product]
        wx.navigateTo({url: '/pages/total/total?list=' + JSON.stringify([this.data.product])})
      } else {  //加购
        let that = this
        wx.request({
          url: that.data.globalData.server + '/cart',
          method: 'POST',
          data: {
            userId: wx.getStorageSync('user').userId,
            productId: this.data.product.productId,
            count: this.data.count
          },
          success(res) {
            that.hideBuy()
            wx.showToast({
              title: '加购成功',
            })
          },
        })
      }
    }
  }
  

})